/*
@Time : 2018/11/12 上午10:54 
@Author : baoye
@File : commandLine
@Software: GoLand
@brief: 
*/

package main

import (
	"fmt"
	"os"
)

func (cli *CLI)AddBlock(txs []*Transaction) {
	bc := GetBlockChainObj()
	bc.AddBlock(txs)
	bc.db.Close()
	fmt.Println("add block successfully")
}

func (cli *CLI)PrintChain()  {
	bc := GetBlockChainObj()
	it := NewBlockchainIter(*bc)
	for ; ;  {
		block := it.GetBlockAndMoveLeft()
		fmt.Printf("=================\n")
		fmt.Printf("PrevBlockHash:%x\n", block.PrevBlockHash)
		fmt.Printf("Version :%v\n", block.Version)
		fmt.Printf("Hash :%x\n", block.Hash)
		fmt.Printf("Nonce :%v\n", block.Nonce)
		fmt.Printf("Difficulty :%v\n", block.Difficulty)
		fmt.Printf("TimeStamp :%v\n", block.TimeStamp)
		fmt.Printf("MerkelRoot :%v\n", block.MerkelRoot)
		fmt.Printf("Data :%s\n", block.Transactions[0].TXInputs[0].ScriptSig)
		pow := NewProofOfWork(block)
		fmt.Printf("IsValid :%v\n", pow.IsValid())
		if it.currentHash == nil {
			break
		}
	}
}

func (cli *CLI)CreateBlockChain(address string) {
	bc := NewBlockChain(address)
	err := bc.db.Close()
	if err != nil {
		if dbExists() {
			os.Remove(BlockChainDB)
		}
		fmt.Println("create blockchain failed!")
	}

	fmt.Println("create blockchain successfully")
}

func (cli *CLI)GetBalance(address string)  {
	bc := GetBlockChainObj()
	defer bc.db.Close()

	utxos := bc.FindUTXOs(address)

	var total float64
	for _, utxo := range utxos{
		total += utxo.Value
	}

	fmt.Printf("The balance of %s is : %f\n", address, total)
}

func (cli *CLI)Send(from, to string, amount float64, miner string)  {
	bc := GetBlockChainObj()
	tx := NewTransaction(from, to, amount, bc)
	defer bc.db.Close()

	coinbase := NewCoinbaseTX(miner, "")
	bc.AddBlock([]*Transaction{coinbase, tx})

	fmt.Println("Send successfully!")
}